// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 获取搜索相关元素
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const timelineItems = document.querySelectorAll('.timeline-item');

    // 搜索功能
    function performSearch() {
        const searchTerm = searchInput.value.trim().toLowerCase();
        
        if (searchTerm === '') {
            // 如果搜索词为空，显示所有项目
            timelineItems.forEach(item => {
                item.style.display = 'block';
                removeHighlight(item);
            });
            return;
        }

        let hasResults = false;
        
        timelineItems.forEach(item => {
            const content = item.textContent.toLowerCase();
            const title = item.querySelector('h3').textContent.toLowerCase();
            const year = item.querySelector('.year').textContent.toLowerCase();
            
            if (content.includes(searchTerm) || title.includes(searchTerm) || year.includes(searchTerm)) {
                item.style.display = 'block';
                highlightSearchTerm(item, searchTerm);
                hasResults = true;
                
                // 平滑滚动到第一个搜索结果
                if (!hasResults) {
                    item.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            } else {
                item.style.display = 'none';
            }
        });

        // 显示搜索结果提示
        if (!hasResults) {
            showNoResultsMessage();
        }
    }

    // 高亮搜索词
    function highlightSearchTerm(element, searchTerm) {
        removeHighlight(element);
        
        const walker = document.createTreeWalker(
            element,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        const textNodes = [];
        let node;
        while (node = walker.nextNode()) {
            textNodes.push(node);
        }

        textNodes.forEach(textNode => {
            const text = textNode.textContent;
            const regex = new RegExp(`(${searchTerm})`, 'gi');
            
            if (regex.test(text)) {
                const highlightedText = text.replace(regex, '<span class="highlight">$1</span>');
                const span = document.createElement('span');
                span.innerHTML = highlightedText;
                textNode.parentNode.replaceChild(span, textNode);
            }
        });
    }

    // 移除高亮
    function removeHighlight(element) {
        const highlights = element.querySelectorAll('.highlight');
        highlights.forEach(highlight => {
            const parent = highlight.parentNode;
            parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
            parent.normalize();
        });
    }

    // 显示无结果消息
    function showNoResultsMessage() {
        // 移除之前的消息
        const existingMessage = document.querySelector('.no-results-message');
        if (existingMessage) {
            existingMessage.remove();
        }

        const message = document.createElement('div');
        message.className = 'no-results-message';
        message.style.cssText = `
            text-align: center;
            padding: 20px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            margin: 20px auto;
            max-width: 400px;
            color: #666;
        `;
        message.innerHTML = `
            <p>未找到包含"${searchInput.value}"的历史事件</p>
            <p>请尝试其他关键词</p>
        `;

        const timelineContainer = document.querySelector('.timeline-container');
        timelineContainer.insertBefore(message, timelineContainer.firstChild);
    }

    // 绑定搜索事件
    searchBtn.addEventListener('click', performSearch);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });

    // 实时搜索（可选，取消注释启用）
    // searchInput.addEventListener('input', debounce(performSearch, 300));

    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 添加滚动动画
    function addScrollAnimation() {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        });

        timelineItems.forEach(item => {
            observer.observe(item);
        });
    }

    // 添加点击展开/收起功能
    function addExpandCollapse() {
        timelineItems.forEach(item => {
            const content = item.querySelector('.timeline-content');
            const details = item.querySelector('.details');
            
            if (details) {
                // 创建展开/收起按钮
                const toggleBtn = document.createElement('button');
                toggleBtn.className = 'toggle-details';
                toggleBtn.innerHTML = '展开详情';
                toggleBtn.style.cssText = `
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    color: white;
                    border: none;
                    padding: 8px 16px;
                    border-radius: 20px;
                    cursor: pointer;
                    font-size: 0.9rem;
                    margin-top: 15px;
                    transition: all 0.3s ease;
                `;

                // 初始隐藏详情
                details.style.display = 'none';
                
                // 插入按钮
                const timelineBody = item.querySelector('.timeline-body');
                timelineBody.appendChild(toggleBtn);

                // 点击事件
                toggleBtn.addEventListener('click', function() {
                    if (details.style.display === 'none') {
                        details.style.display = 'block';
                        toggleBtn.innerHTML = '收起详情';
                        toggleBtn.style.background = 'linear-gradient(135deg, #e74c3c, #c0392b)';
                    } else {
                        details.style.display = 'none';
                        toggleBtn.innerHTML = '展开详情';
                        toggleBtn.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
                    }
                });
            }
        });
    }

    // 添加平滑滚动到顶部功能
    function addScrollToTop() {
        const scrollTopBtn = document.createElement('button');
        scrollTopBtn.innerHTML = '↑';
        scrollTopBtn.className = 'scroll-top-btn';
        scrollTopBtn.style.cssText = `
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
        `;

        document.body.appendChild(scrollTopBtn);

        // 滚动事件
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                scrollTopBtn.style.opacity = '1';
                scrollTopBtn.style.visibility = 'visible';
            } else {
                scrollTopBtn.style.opacity = '0';
                scrollTopBtn.style.visibility = 'hidden';
            }
        });

        // 点击回到顶部
        scrollTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });

        // 悬停效果
        scrollTopBtn.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.1)';
        });

        scrollTopBtn.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    }

    // 添加键盘导航功能
    function addKeyboardNavigation() {
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                // ESC键清空搜索
                searchInput.value = '';
                performSearch();
                searchInput.focus();
            }
        });
    }

    // 初始化所有功能
    function init() {
        addScrollAnimation();
        addExpandCollapse();
        addScrollToTop();
        addKeyboardNavigation();
        
        // 添加加载完成后的淡入效果
        setTimeout(() => {
            document.body.style.opacity = '1';
        }, 100);
    }

    // 启动应用
    init();
});

// 添加一些额外的交互效果
window.addEventListener('load', function() {
    // 页面加载完成后的动画
    const timelineItems = document.querySelectorAll('.timeline-item');
    
    timelineItems.forEach((item, index) => {
        item.style.animationDelay = `${index * 0.1}s`;
    });
}); 